import { useEffect, useState } from "react";
import { flushSync } from "react-dom";
import "./index.less";
import { getInfo, queryStoryExtra, setStore } from "./../../service/api";
import { Skeleton, Toast } from "antd-mobile";
import {
  HeartOutline,
  LikeOutline,
  StarOutline,
  UploadOutline,
  LeftOutline,
} from "antd-mobile-icons";
import NavBarAgain from "./../../components/NavBarAgain";

const Details = (props) => {
  const { navigate } = props;
  const newsId = props.params?.id;
  let [detailsData, setDetailsData] = useState({});
  let [storyExtra, setStoryExtra] = useState({});
  let [isCollect, setIsCollect] = useState(false);

  /* 获取当前新闻详情 */
  const getNewsDetails = async () => {
    if (newsId) {
      try {
        const data = await getInfo(newsId);
        flushSync(() => {
          setDetailsData(data);
          createStyleCSS(data);
        });
        handleImage(data);
      } catch (error) {
        console.log("内容详情接口查询失败 ...", error);
      }
    }
  };

  const handleImage = (result) => {
    let imgPlaceHolder = document.querySelector(".img-place-holder");
    if (!imgPlaceHolder) return;
    // 创建大图
    let tempImg = new Image();
    tempImg.src = result.image;
    tempImg.onload = () => {
      imgPlaceHolder.appendChild(tempImg);
    };
    tempImg.onerror = () => {
      let parent = imgPlaceHolder.parentNode;
      parent.parentNode.removeChild(parent);
    };
  };

  /* 获取当前新闻点赞数和评论量 */
  const getNewsDetailsNumber = async () => {
    if (newsId) {
      try {
        const dta = await queryStoryExtra(newsId);
        setStoryExtra(dta);
      } catch (error) {
        console.log("获取新闻点赞信息失败 ...", error);
      }
    }
  };

  /* 动态创建CSS表 */
  let link;
  const createStyleCSS = (data) => {
    let { css } = data;
    if (Array.isArray(css)) {
      if (css[0]) {
        link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = css[0];
        document.head.appendChild(link);
      }
    }
  };

  /* 收藏当前新闻 */
  const handleCollect = async () => {
    //没有登录去登录页面，登录成功后自动再次跳进来，进行收藏！
    if (!window.localStorage.getItem("tk")) {
      navigate(`/login?to=details/${newsId}`);
      return;
    }
    if (newsId) {
      const { code } = await setStore(props.params?.id);
      if (code === 0) {
        Toast.show({
          icon: "success",
          content: "收藏成功",
        });
        setIsCollect(true);
        return;
      }

      Toast.show({
        icon: "fail",
        content: "收藏失败",
      });
    }
  };

  /* 第一次渲染完毕：获取数据。以后组件状态更新，只是UI试图更新，不在重新绘制了 */
  useEffect(() => {
    getNewsDetails();
    getNewsDetailsNumber();
  }, []);

  useEffect(() => {
    /*  组件卸载删除对应样式  */
    return () => {
      if (link) document.head.removeChild(link);
    };
  }, []);

  return (
    <div className="details-page">
      <NavBarAgain title="新闻详情" />
      {/* <div className="cover-img-box">
        <img src={detailsData.image} alt="" />
        <h2>{detailsData.title}</h2>
      </div> */}
      {/* <div>
        <Skeleton.Title animated />
        <Skeleton.Paragraph animated />
      </div> */}
      <div className="content">
        {/* <h2>11111</h2>
        <p>
          <span>{detailsData.a}</span>
          <span
            className="origin-view"
            onClick={() => {
              window.open(detailsData.url, "_self");
            }}
          >
            进入知乎查看原文
          </span>
        </p> */}

        <div className="content-desc">
          {/*
           * 基于胡子语法绑定的内容，全部会作为普通文本，进行渲染！
           * 如果想把内容中的HTML字符串识别为HTML标记，要基于这个语法!
           *  dangerouslySetInnerHTML = {{_html: HTML字符串}}
           */}
          <div dangerouslySetInnerHTML={{ __html: detailsData.body }}></div>
        </div>
      </div>

      <div className="footer-bar">
        <div
          className="footer-bar-item"
          onClick={() => {
            props.navigate(-1);
          }}
        >
          <LeftOutline />
        </div>
        <div className="footer-bar-item">
          <HeartOutline />
          <span>{storyExtra.comments}</span>
        </div>
        <div className="footer-bar-item">
          <LikeOutline />
          <span>{storyExtra.popularity}</span>
        </div>
        <div className="footer-bar-item" onClick={handleCollect}>
          <StarOutline className={isCollect ? "collect-mark" : ""} />
        </div>
        <div className="footer-bar-item">
          <UploadOutline />
        </div>
      </div>
    </div>
  );
};

export default Details;
